<template>
  <create-view
    :body-style="{ height: '100%'}">
    <flexbox
      v-loading="loading"
      direction="column"
      class="create-container">
      <flexbox class="create-header">
        <flexbox-item class="create-header_title">
          {{ id ? '编辑' : '新建' }}{{ typeObj.name || '' }}
        </flexbox-item>
        <i
          class="el-icon-close create-header_close"
          @click="handleClose" />
      </flexbox>

      <flexbox-item
        v-if="fieldsLib && showForm"
        style="margin-left: 0"
        class="create-body">

        <create-sections title="基本信息">
          <wk-form
            v-if="baseForm"
            ref="wkFormBase"
            :model="baseForm"
            :rules="baseRules"
            :field-from="baseForm"
            :field-list="fieldsLib.base"
            label-position="top"
            @change="handleFormChange">
            <template slot-scope="scope">
              <wk-file-form
                v-if="scope.data.formType === 'file'"
                :default-value="scope.data.value || []"
                @change="handleFileChange(scope, ...arguments)" />
              <wk-product-category
                v-if="scope.data.formType === 'category'"
                v-model="baseForm[scope.data.field]"
                @change="handleProductCategory(scope.data)" />
              <xh-customer-address
                v-if="scope.data.formType === 'map_address'"
                :value="addressData"
                @value-change="handleAddressChange" />
              <relative-choose
                v-if="showRelativeFn(scope.data.formType)"
                v-model="baseForm[scope.data.field]"
                :field="scope.data"
                :params="relativeParams(scope.data.formType)"
                :form-type="scope.data.formType"
                :disabled="scope.data.disabled"
                @change="relativeChange" />
            </template>
          </wk-form>

          <product-all-cell
            v-if="showProductChoose"
            :type="type"
            :relative-type="relativeType"
            :default-value="productList"
            :default-rate="defaultRate"
            :config="relativeData"
            @change="handleProductChange" />
        </create-sections>

        <create-sections
          v-if="showReceiveAddress"
          title="收货地址">
          <wk-form
            ref="receiveAddress"
            :model="receiveAddressForm"
            :rules="receiveAddressRules"
            :field-from="receiveAddressForm"
            :field-list="receiveAddressFieldList"
            label-position="top" />
        </create-sections>

        <create-sections
          v-if="type === 'jxc_product'"
          title="产品规格">
          <product-size
            v-model="productSizeForm"
            :auto-number="autoGeneNumber"
            :default-value="productSizeDefault" />
        </create-sections>

        <create-sections
          v-if="showImage"
          title="图片信息">
          <image-form
            v-for="(item, index) in imageFields"
            :key="index"
            :field="item"
            :default-value="item.value || []"
            :label="item.name"
            :tips="item.inputTips"
            :init-batch-id="initImgBatchId"
            @change="handleImgChange" />
        </create-sections>

        <create-sections
          v-if="showExamine"
          title="审核信息">
          <template slot="header">
            <div
              v-if="examineInfo.examineType===1 || examineInfo.examineType===2"
              class="examine-type">{{ examineInfo.examineType===1 ? '固定审批流' : '授权审批人' }}</div>
            <el-tooltip
              v-if="examineInfo && examineInfo.remarks"
              :content="examineInfo.remarks"
              effect="dark"
              placement="top">
              <i class="wk wk-help wk-help-tips" style="height: 13px;"/>
            </el-tooltip>
          </template>
          <create-examine-info
            ref="examineInfo"
            :types="type"
            :types-id="id"
            @info="handleExamineInfo" />
        </create-sections>

      </flexbox-item>

      <div class="create-footer">
        <product-sync-update
          v-if="showProductSize && id"
          @confirm="handleSyncFields" />
        <el-button
          type="primary"
          @click="handleSave">
          保存
        </el-button>
        <el-button @click="handleClose">
          取消
        </el-button>
      </div>
    </flexbox>
  </create-view>
</template>

<script>
import { jxcFieldQueryFieldAPI, jxcFieldOnlyAPI, jxcFieldOderNumberOnlyAPI } from '@/api/jxc/field'
import { jxcProductAddOrUpdateAPI } from '@/api/jxc/product'
import { jxcSupplierAddOrUpdateAPI } from '@/api/jxc/supplier'
import { jxcPurchaseAddOrUpdateAPI } from '@/api/jxc/purchase'
import { jxcRetreatAddOrUpdateAPI } from '@/api/jxc/retreat'
import { jxcSaleAddOrUpdateAPI } from '@/api/jxc/sale'
import { jxcSalereturnAddOrUpdateAPI } from '@/api/jxc/saleReturn'
import { jxcReceiptAddOrUpdateAPI } from '@/api/jxc/receipt'
import { jxcOutboundAddOrUpdateAPI } from '@/api/jxc/outbound'
import { jxcCollectionAddOrUpdateAPI } from '@/api/jxc/collection'
import { jxcPaymentAddOrUpdateAPI } from '@/api/jxc/payment'
import { jxcAllocationAddOrUpdateAPI } from '@/api/jxc/allocation'
import { jxcInventoryAddOrUpdateAPI } from '@/api/jxc/inventory'

import { userListAPI } from '@/api/common'
import { depListAPI } from '@/api/common'

import CreateView from '@/components/CreateView'
import CreateSections from '@/components/CreateSections'
import ProductSize from './components/ProductSize'
import RelativeChoose from './components/RelativeChoose'
import ProductSyncUpdate from './components/ProductSyncUpdate'
import ProductAllCell from './ProductAllCell'
import ImageForm from '@/components/NewCom/WkImage/imageForm'

import WkForm from '@/components/NewCom/WkForm'
import WkProductCategory from '@/components/NewCom/WkProductCategory'
import CreateExamineInfo from '@/components/NewCom/WkExamine/CreateExamineInfo'
import XhCustomerAddress from '@/components/CreateCom/XhCustomerAddress'
import WkFileForm from '@/components/NewCom/WkFile/Form/index'

import GenerateRulesMixin from '@/components/NewCom/WkForm/GenerateRules'
import jxcTypes from '../../jxcTypes'
import { objDeepCopy } from '@/utils'
import { isArray, isEmpty } from '@/utils/types'
import ReceiveAddressMixin from './ReceiveAddress' // 收货地址逻辑
import ExamineMixin from './Examine'
import { mapGetters } from 'vuex'

export default {
  name: 'CreateCom',
  components: {
    CreateView,
    CreateSections,
    ProductSize,
    WkProductCategory,
    ImageForm,
    WkForm,
    WkFileForm,
    CreateExamineInfo,
    XhCustomerAddress,
    RelativeChoose,
    ProductAllCell,
    ProductSyncUpdate
  },
  mixins: [GenerateRulesMixin, ReceiveAddressMixin, ExamineMixin],
  props: {
    // 类型
    type: {
      type: String,
      required: true
    },
    // 编辑时传id
    id: {
      type: [String, Number],
      default: null
    },
    // 批次ID
    batchId: {
      type: String
    },
    /**
     * 初始配置
     * {
     *   defaultValue: Object  初始默认值
     *   disabledField: String[] 禁止修改的字段
     * }
     */
    config: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,

      fieldsLib: null, // 字段库
      staticFieldsLib: null, // 原始字段库拷贝
      baseForm: null,
      baseRules: {},
      showForm: true,

      productSizeForm: {}, // 产品规格表单数据
      productSizeDefault: null, // 未经处理的产品规格默认数据
      productDetailImgList: [], // 产品详情图

      productList: [], // 相关产品列表数据
      defaultRate: 0,
      relativeType: null,

      imageFields: [],
      imageFrom: {},
      addressData: null,

      syncProductFields: [], // 编辑产品时同步修改的字段

      relativeData: {}, // 关联项
      autoGeneNumber: false, // 是否已经开启自动编号规则
      autoNumberField: null // 自动编号规则字段信息
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    typeObj() {
      return jxcTypes[this.type]
    },
    showProductSize() {
      if (this.type !== 'jxc_product') return false
      if (this.id) {
        if (this.staticFieldsLib && this.staticFieldsLib.jxcProduct.productIsp == 0) {
          return false
        }
      }
      return true
    },
    initImgBatchId() {
      return Boolean(this.type === 'jxc_product' && this.id)
    },
    showImage() {
      return this.imageFields.length > 0
    },
    showProductChoose() {
      return [
        'jxc_purchase',
        'jxc_retreat',
        'jxc_sale',
        'jxc_salereturn',
        'jxc_receipt',
        'jxc_outbound',
        'jxc_allocation',
        'jxc_inventory'
      ].includes(this.type)
    }
  },
  created() {
    this.getFieldList()
  },
  methods: {
    /**
     * 获取字段列表
     */
    getFieldList() {
      this.loading = true
      const params = {
        label: this.typeObj.label
      }
      if (this.id) {
        params.id = this.id
      }
      this.autoGeneNumber = false
      jxcFieldQueryFieldAPI(params).then(res => {
        console.log('field res: ', res)
        this.loading = false
        this.baseForm = null
        const form = {}
        const arr = []
        const imageFields = []
        res.data.base.forEach(item => {
          item.field = item.fieldName
          if (item.autoGeneNumber === 1) {
            item.placeholder = '根据编号规则自动生成，支持手动输入'
            this.autoGeneNumber = true
            this.autoNumberField = item
          }

          if (item.formType === 'user' || item.formType === 'single_user') {
            item.request = userListAPI
            item.params = { pageType: 0 }
            item.radio = item.formType === 'single_user'
          } else if (item.formType === 'structure') {
            item.request = depListAPI
            item.props = {
              value: 'deptId',
              label: 'name'
            }
          } else if (['file', 'map_address'].includes(item.formType)) {
            item.className = 'block_one_line'
          }

          this.baseRules[item.fieldName] = this.getRules(item)

          if (item.formType === 'pic' && item.fieldName !== 'productPicture') {
            imageFields.push(item)
            this.imageFrom[item.fieldName] = this.getDefaultValue(item)
          } else {
            arr.push(item)
            form[item.fieldName] = this.getDefaultValue(item)
          }
        })
        if (this.type === 'jxc_product' && !this.id) {
          const findIndex = arr.findIndex(o => o.fieldName === 'productCode')
          if (findIndex !== -1) {
            arr.splice(findIndex, 1)
          }
        }
        res.data.base = arr
        this.imageFields = imageFields
        this.baseForm = form

        this.staticFieldsLib = objDeepCopy(res.data)
        if (this.id) {
          // 如果是编辑则渲染表单原有的关联产品
          if (this.type === 'jxc_product') {
            this.formatProductField(res.data)
            return
          } else if (this.type === 'jxc_purchase') {
            this.productList = res.data.purchasesProductList
            this.baseForm.discount = res.data.jxcPurchase.discount || 0
            this.defaultRate = this.baseForm.discount
          } else if (this.type === 'jxc_sale') {
            this.productList = res.data.jxcSaleProductList
            this.baseForm.discount = res.data.jxcSale.discount || 0
            this.defaultRate = this.baseForm.discount
            this.setDefaultReceiveAddress(res.data.jxcSale || {})
          } else if (this.type === 'jxc_allocation') {
            this.productList = res.data.jxcAllocationProductList
          } else if (this.type === 'jxc_inventory') {
            this.productList = res.data.jxcInventoryProductList
          }
        }

        this.fieldsLib = objDeepCopy(res.data)
        if (['jxc_receipt', 'jxc_outbound'].includes(this.type)) {
          // 入库、出库根据出入库类型渲染不同的表单
          const findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'orderId')
          if (findIndex !== -1) {
            this.fieldsLib.base.splice(findIndex, 1)
          }

          // 如果有默认类型则立即去计算关联表单
          if (this.type === 'jxc_receipt' && this.baseForm.receiptType) {
            this.renderReceiptForm(null, null, this.baseForm.receiptType)
          } else if (this.type === 'jxc_outbound' && this.baseForm.outboundType) {
            this.renderOutboundForm(null, null, this.baseForm.outboundType)
          }
        } else if (['jxc_collection', 'jxc_payment'].includes(this.type)) {
          // 回款、付款根据类型渲染不同的表单
          let findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'relatedId')
          if (findIndex !== -1) {
            this.fieldsLib.base.splice(findIndex, 1)
          }
          findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'collectionObject')
          if (findIndex !== -1) {
            this.fieldsLib.base.splice(findIndex, 1)
          }

          const key = this.type === 'jxc_collection' ? 'collectionType' : 'paymentType'
          // 如果有默认类型则立即去计算关联表单
          if (this.baseForm[key]) {
            this.renderCollectionForm(null, null, this.baseForm[key])
          }
        }
        this.setDisabledField()
      }).catch(() => {
        this.loading = false
        this.fieldsLib = null
        this.staticFieldsLib = null
      })
    },

    showRelativeFn(formType) {
      return [
        'supplier_cause',
        'purchase_cause',
        'sale_cause',
        'customer',
        'warehouse_cause',
        'retreat_cause',
        'salereturn_cause'
      ].includes(formType)
    },

    /**
     * 编辑产品时初始化表单数据
     */
    formatProductField(data) {
      // 产品编辑时删除规格字段
      let findIndex = data.base.findIndex(o => o.fieldName === 'spDataValue')
      if (findIndex !== -1) {
        data.base.splice(findIndex, 1)
      }
      // 产品编辑时删除产品编码字段
      findIndex = data.base.findIndex(o => o.fieldName === 'productCode')
      if (findIndex !== -1) {
        data.base.splice(findIndex, 1)
      }

      // 取产品主图 productPicture
      findIndex = data.base.findIndex(o => o.fieldName === 'productPicture')
      let productPicture = null
      if (findIndex !== -1) {
        const val = data.base[findIndex].value
        productPicture = isArray(val) && val.length > 0 ? val[0] : null
        data.base.splice(findIndex, 1)
      }
      this.productSizeDefault = {
        jxcProduct: data.jxcProduct,
        jxcProductSpecificationsData: {
          // ...data.jxcProductSpecificationsData,
          ...data.jxcProduct,
          spDataCode: data.jxcProduct.productCode,
          img: productPicture
        }
      }
      this.fieldsLib = data
    },

    /**
     * 添加默认值
     */
    getDefaultValue(field) {
      if (this.config && this.config.defaultValue) {
        const defaultVal = this.config.defaultValue
        if (defaultVal.hasOwnProperty(field.field)) {
          field.value = defaultVal[field.field]
          return defaultVal[field.field]
        }
      }
      if (field.formType === 'map_address') {
        this.addressData = field.value || {}
        if (this.addressData.address) {
          this.addressData.address = this.addressData.address.split(',')
        }
        return {}
      } else if (field.formType === 'single_user') {
        if (!field.value) {
          if (field.fieldName === 'ownerUserId') {
            return this.userInfo.userId
          }
          return ''
        }
        if (isArray(field.value) && field.value.length > 0) return field.value[0]
        return field.value || field.defaultValue || ''
      } else if (field.formType === 'user') {
        let arr = []
        if (isArray(field.value)) {
          arr = field.value.map(o => Number(o))
        }
        if (field.value) {
          arr.push(field.value)
        }
        if (arr.length === 0 && field.fieldName === 'ownerUserId') {
          arr.push(this.userInfo.userId)
        }
        return arr
      } else if (field.formType === 'category') {
        return Number(field.value) || null
      } else if (field.formType === 'pic' || field.formType === 'file') {
        if (isArray(field.value)) {
          return field.value.length > 0 ? field.value[0].batchId : ''
        }
        return ''
      } else {
        return field.value || field.defaultValue || ''
      }
    },

    /**
     * 设置禁用项
     */
    setDisabledField() {
      if (this.type === 'jxc_retreat') {
        const findIndex = this.fieldsLib.base.findIndex(o => o.formType === 'supplier_cause')
        if (findIndex !== -1) {
          this.fieldsLib.base[findIndex].disabled = true
          this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
        }
      } else if (this.type === 'jxc_salereturn') {
        const findIndex = this.fieldsLib.base.findIndex(o => o.formType === 'customer')
        if (findIndex !== -1) {
          this.fieldsLib.base[findIndex].disabled = true
          this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
        }
      }
      if (this.config && this.config.disabledField) {
        this.config.disabledField.forEach(key => {
          const findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === key)
          if (findIndex !== -1) {
            this.fieldsLib.base[findIndex].disabled = true
            this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
          }
        })
      }
      console.log('setDisabledField--', this.fieldsLib)
    },

    /**
     * 关闭表单
     */
    handleClose() {
      this.$emit('close')
    },

    /**
     * 关联项值发生变化后校验
     */
    relativeChange(field, data) {
      this.$set(this.relativeData, field.field, this.baseForm[field.field])
      if (this.id) {
        this.$set(this.relativeData, 'editBatchId', this.batchId)
      }
      if (this.$refs.wkFormBase) {
        const instance = this.$refs.wkFormBase.instance
        instance.validateField(field.field)
        // this.setDisabledField()

        if (
          this.type === 'jxc_retreat' &&
          field.field === 'purchaseId') {
          // 采购退货--选择采购单后
          if (data.data.length > 0) {
            this.baseForm.supplierId = data.data[0].supplierId
            this.$set(this.baseForm, 'supplierId', data.data[0].supplierId)
          } else {
            this.$set(this.baseForm, 'supplierId', '')
          }
          // this.$set(this.relativeData, field.field, data.data[0].batchId)
        }
        if (
          this.type === 'jxc_salereturn' &&
          field.field === 'saleId') {
          // 销售退货--选择销售单后
          if (data.data.length > 0) {
            const c_data = data.data[0].customerName
            this.$set(this.baseForm, 'customerName', c_data)
          } else {
            this.$set(this.baseForm, 'customerName', '')
          }
          // this.$set(this.relativeData, field.field, data.data[0].batchId)
        }

        if (
          this.type === 'jxc_sale' &&
          field.field === 'customerName') {
          // 销售--选择客户后
          if (data.data.length > 0) {
            // this.receiveAddressForm = {
            //   discount: data.discount,
            //   contacts: data.data[0].ownerUserName,
            //   telephone: data.data[0].mobile,
            //   detailAddress: data.data[0].detailAddress
            // }
            this.setDefaultReceiveAddress(data.data[0])
          } else {
            this.receiveAddressForm = {
              contacts: '',
              telephone: '',
              detailAddress: ''
            }
          }
        }

        console.log('choose relation: ', data)
        if (
          this.type === 'jxc_collection' &&
          field.field === 'relatedId') {
          // 回款--选择关联单后
          if (data.data.length > 0) {
            let c_data = {}
            if (this.relativeType === 'sale_cause') {
              c_data = data.data[0].customerName
              // this.$set(this.baseForm, 'collectionAmount', data.data[0].salePrice || 0)
            } else if (this.relativeType === 'retreat_cause') {
              c_data = data.data[0].supplierId
              // this.$set(this.baseForm, 'collectionAmount', data.data[0].totalPrice || 0)
            }
            this.$set(this.baseForm, 'collectionObject', c_data)
          } else {
            this.$set(this.baseForm, 'collectionAmount', 0)
            this.$set(this.baseForm, 'collectionObject', '')
          }
        }

        if (
          this.type === 'jxc_payment' &&
          field.field === 'relatedId') {
          // 付款--选择关联单后
          if (data.data.length > 0) {
            let c_data = {}
            if (this.relativeType === 'salereturn_cause') {
              c_data = data.data[0].customerName
            } else if (this.relativeType === 'purchase_cause') {
              c_data = data.data[0].supplierId
            }
            // this.$set(this.baseForm, 'paymentAmount', data.data[0].totalPrice || 0)
            this.$set(this.baseForm, 'collectionObject', c_data)
          } else {
            this.$set(this.baseForm, 'paymentAmount', 0)
            this.$set(this.baseForm, 'collectionObject', '')
          }
        }
      }
    },

    /**
     * 关联项数据列表附加参数
     */
    relativeParams(formType) {
      if (this.type === 'jxc_retreat') {
        // 采购退货 -> 采购单
        if (formType === 'purchase_cause') {
          const list = [
            {
              formType: 'text',
              type: 1,
              name: 'state', // 审核已完成
              values: [3]
            },
            {
              formType: 'text',
              type: 2,
              name: 'return_status',
              values: [2]
            }
          ]
          if (this.config &&
            this.config.defaultValue &&
            this.config.defaultValue.supplierId &&
            this.config.defaultValue.supplierId.id) {
            list.push({
              formType: 'text',
              type: 1,
              name: 'supplier_id', // 固定供应商
              values: [this.config.defaultValue.supplierId.id]
            })
          }
          return {
            searchList: list
          }
        }
      } else if (this.type === 'jxc_receipt') {
        // 入库 -> 采购单
        if (formType === 'purchase_cause') {
          return {
            searchList: [
              {
                formType: 'text',
                type: 1,
                name: 'state', // 审核已完成
                values: [3]
              },
              {
                formType: 'text',
                type: 2,
                name: 'return_status', // 没有全部退货
                values: [2]
              },
              {
                formType: 'text',
                type: 2,
                name: 'warehousing_status', // 没有全部入库
                values: [1]
              }
            ]
          }
        } else if (formType === 'salereturn_cause') {
          return {
            searchList: [
              {
                formType: 'text',
                type: 1,
                name: 'state', // 审核已完成
                values: [3]
              },
              {
                formType: 'text',
                type: 2,
                name: 'warehousing_status', // 没有全部入库
                values: [1]
              }
            ]
          }
        }
      } else if (this.type === 'jxc_salereturn') {
        // 销售退货 -> 销售单
        if (formType === 'sale_cause') {
          return {
            searchList: [
              {
                formType: 'text',
                type: 1,
                name: 'state', // 审核已完成
                values: [3]
              },
              {
                formType: 'text',
                type: 2,
                name: 'return_status', // 没有全部退货
                values: [2]
              }
            ]
          }
        }
      } else if (this.type === 'jxc_outbound') {
        // 出库 -> 采购退货单
        //     -> 销售单
        if (['retreat_cause', 'sale_cause'].includes(formType)) {
          return {
            searchList: [
              {
                formType: 'text',
                type: 1,
                name: 'state', // 审核已完成
                values: [3]
              },
              {
                formType: 'text',
                type: 2,
                name: 'warehousing_status', // 没有全部出库
                values: [1]
              }
            ]
          }
        }
      } else if (this.type === 'jxc_collection') {
        // 回款 -> 销售单
        //     -> 采购退货单
        if (['sale_cause', 'retreat_cause'].includes(formType)) {
          return {
            searchList: [{
              formType: 'text',
              type: 1,
              name: 'state', // 审核已完成
              values: [3]
            }]
          }
        }
      } else if (this.type === 'jxc_payment') {
        // 付款 -> 采购单
        //     -> 销售退货单
        if (['purchase_cause', 'salereturn_cause'].includes(formType)) {
          return {
            searchList: [{
              formType: 'text',
              type: 1,
              name: 'state', // 审核已完成
              values: [3]
            }]
          }
        }
      }
      return {}
    },

    /**
     * 地址类型处理
     */
    handleAddressChange(data) {
      // console.log('data: ', data.value)
      this.addressData = data.value
    },

    /**
     * 修改产品类别
     */
    handleProductCategory(field) {
      if (this.type === 'jxc_inventory' && field.fieldName === 'productType') {
        this.$set(this.relativeData, 'productType', this.baseForm.productType)
      }
    },

    /**
     * 相关产品处理
     */
    handleProductChange(data) {
      if (this.type === 'jxc_purchase') {
        if (this.baseForm.hasOwnProperty('totalPrice')) {
          this.baseForm.totalPrice = data.total
          this.baseForm.discount = data.discount
        }
      } else if (this.type === 'jxc_retreat') {
        if (this.baseForm.hasOwnProperty('totalPrice')) {
          this.baseForm.totalPrice = data.total
        }
      } else if (this.type === 'jxc_sale') {
        if (this.baseForm.hasOwnProperty('salePrice')) {
          this.baseForm.salePrice = data.total
          this.baseForm.discount = data.discount
        }
      } else if (this.type === 'jxc_salereturn') {
        if (this.baseForm.hasOwnProperty('totalPrice')) {
          this.baseForm.totalPrice = data.total
        }
      }
      this.productList = data.data
    },

    /**
     * 产品图片处理
     */
    handleImgChange(field, batchId = null, imageList = []) {
      console.log('image change: ', imageList, batchId)
      this.imageFrom[field.fieldName] = batchId || ''
    },

    handleFileChange(scope, list, batchId) {
      if (list.length === 0) {
        this.baseForm[scope.data.field] = ''
      } else {
        this.baseForm[scope.data.field] = batchId || ''
      }
    },

    /**
     * wk-form 表单值变化
     */
    handleFormChange(field, index, value) {
      // 切换入库类型
      if (this.type === 'jxc_receipt' && field.field === 'receiptType') {
        this.renderReceiptForm(field, index, value)
        this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
        // 重新渲染表单防止关联项popover渲染错误
        this.updateForm()
      }
      // 切换出库类型
      if (this.type === 'jxc_outbound' && field.field === 'outboundType') {
        this.renderOutboundForm(field, index, value)
        this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
        // 重新渲染表单防止关联项popover渲染错误
        this.updateForm()
      }
      // 切换回款类型
      if (this.type === 'jxc_collection' && field.field === 'collectionType') {
        this.renderCollectionForm(field, index, value)
        this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
        this.$set(this.baseForm, 'collectionAmount', 0)
        this.updateForm()
      }
      // 切换付款类型
      if (this.type === 'jxc_payment' && field.field === 'paymentType') {
        this.renderCollectionForm(field, index, value)
        this.$set(this.fieldsLib, 'base', this.fieldsLib.base)
        this.$set(this.baseForm, 'paymentAmount', 0)
        this.updateForm()
      }
    },

    /**
     * 验证唯一
     */
    UniquePromise(data) {
      // jxcFieldOderNumberOnlyAPI
      return new Promise((resolve, reject) => {
        console.log('FieldOnly', data)
        if (data.field.autoGeneNumber === 1 && !data.value) {
          jxcFieldOderNumberOnlyAPI({
            label: this.typeObj.label
          }).then(res => {
            if (res.data) {
              resolve()
            } else {
              reject(`自动编号有重复`)
            }
          }).catch(() => {
            reject()
          })
          return
        }

        if (!data.value) {
          resolve()
          return
        }
        const params = {
          fieldName: data.field.fieldName,
          fieldType: data.field.fieldType,
          label: this.typeObj.label,
          value: data.value
        }
        if (this.batchId) {
          params.batchId = this.batchId
        }
        if (this.batchId && this.type === 'jxc_product') {
          params.batchId = this.staticFieldsLib.jxcProduct.spBatchId
        }
        jxcFieldOnlyAPI(params).then(res => {
          if (res.data) {
            resolve()
          } else {
            reject(`${data.field.name}不能重复`)
          }
        }).catch(() => {
          reject()
        })
      })
    },

    /**
     * 入库单下的关联
     */
    renderReceiptForm(field, index, value) {
      // console.log('。。。。', field, index, value)
      const findRes = this.staticFieldsLib.base.find(o => o.fieldName === 'orderId')
      const findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'orderId')
      if (findIndex !== -1) {
        this.fieldsLib.base.splice(findIndex, 1)
      }
      delete this.relativeData.orderId
      this.relativeData = {
        ...this.relativeData
      }
      this.relativeType = ''
      if (value === '采购入库' && findRes) {
        this.fieldsLib.base.splice(2, 0, {
          ...findRes,
          formType: 'purchase_cause',
          name: '采购订单'
        })
        this.relativeType = 'purchase_cause'
        this.$set(this.relativeData, 'orderId', '')
      } else if (value === '销售退货入库' && findRes) {
        // 销售退货入库
        this.fieldsLib.base.splice(2, 0, {
          ...findRes,
          formType: 'salereturn_cause',
          name: '销售退货单'
        })
        this.relativeType = 'salereturn_cause'
        this.$set(this.relativeData, 'orderId', '')
      }
    },

    /**
     * 出库单下的关联
     */
    renderOutboundForm(field, index, value) {
      // console.log('。。。。', field, index, value)
      const findRes = this.staticFieldsLib.base.find(o => o.fieldName === 'orderId')
      const findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'orderId')
      if (findIndex !== -1) {
        this.fieldsLib.base.splice(findIndex, 1)
      }
      delete this.relativeData.orderId
      this.relativeData = {
        ...this.relativeData
      }
      this.relativeType = ''
      if (value === '销售出库' && findRes) {
        this.fieldsLib.base.splice(2, 0, {
          ...findRes,
          formType: 'sale_cause',
          name: '销售订单'
        })
        this.relativeType = 'sale_cause'
        this.$set(this.relativeData, 'orderId', '')
      } else if (value === '采购退货出库' && findRes) {
        this.fieldsLib.base.splice(2, 0, {
          ...findRes,
          formType: 'retreat_cause',
          name: '采购退货单'
        })
        this.relativeType = 'retreat_cause'
        this.$set(this.relativeData, 'orderId', '')
      }
    },

    /**
     * 回款/付款单下的关联
     */
    renderCollectionForm(field, index, value) {
      const findRes = this.staticFieldsLib.base.find(o => o.fieldName === 'relatedId')
      const obj = this.staticFieldsLib.base.find(o => o.fieldName === 'collectionObject')
      let findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'relatedId')
      if (findIndex !== -1) {
        this.fieldsLib.base.splice(findIndex, 1)
      }
      findIndex = this.fieldsLib.base.findIndex(o => o.fieldName === 'collectionObject')
      if (findIndex !== -1) {
        this.fieldsLib.base.splice(findIndex, 1)
      }
      delete this.relativeData.relatedId
      delete this.relativeData.collectionObject
      this.relativeData = {
        ...this.relativeData
      }
      this.relativeType = ''
      if (findRes && obj) {
        switch (value) {
          case '采购退货': // 采购退货回款
            this.fieldsLib.base.splice(2, 0, {
              ...findRes,
              formType: 'retreat_cause',
              name: '采购退货单'
            })
            this.fieldsLib.base.splice(3, 0, {
              ...obj,
              formType: 'supplier_cause',
              name: '关联供应商',
              disabled: true
            })
            this.relativeType = 'retreat_cause'
            break
          case '销售': // 销售回款
            this.fieldsLib.base.splice(2, 0, {
              ...findRes,
              formType: 'sale_cause',
              name: '销售订单'
            })

            this.fieldsLib.base.splice(3, 0, {
              ...obj,
              formType: 'customer',
              name: '关联客户',
              disabled: true
            })
            this.relativeType = 'sale_cause'
            break
          case '采购': // 采购付款
            this.fieldsLib.base.splice(2, 0, {
              ...findRes,
              formType: 'purchase_cause',
              name: '采购订单'
            })
            this.fieldsLib.base.splice(3, 0, {
              ...obj,
              formType: 'supplier_cause',
              name: '关联供应商',
              disabled: true
            })
            this.relativeType = 'purchase_cause'
            break
          case '销售退货': // 销售退货付款
            this.fieldsLib.base.splice(2, 0, {
              ...findRes,
              formType: 'salereturn_cause',
              name: '销售退货单'
            })

            this.fieldsLib.base.splice(3, 0, {
              ...obj,
              formType: 'customer',
              name: '关联客户',
              disabled: true
            })
            this.relativeType = 'salereturn_cause'
            break
        }
        this.$set(this.relativeData, 'relatedId', '')
        this.$set(this.baseForm, 'collectionObject', obj.value)
      }
    },

    /**
     * 获取保存的表单数据
     */
    getSaveData() {
      let form = {
        entity: {},
        field: []
      }
      console.log(this.baseForm)
      this.fieldsLib.base.forEach(item => {
        let value = this.baseForm[item.fieldName] || ''
        if (this.baseForm[item.fieldName]) {
          if (['single_user', 'user'].includes(item.formType)) {
            // 员工类型
            value = isArray(value) ? value.join(',') : value
          } else if (item.formType === 'structure' && isArray(value)) {
            // 部门类型
            value = value.map(o => o.deptId || o.id).join(',')
          } else if (item.formType === 'checkbox' && isArray(value)) {
            // 多选类型
            value = value.join(',')
          }
        }
        if (['number', 'floatnumber'].includes(item.formType)) {
          if (isEmpty(value)) {
            value = 0
          }
        }

        if (item.fieldType == 1) {
          form.entity[item.fieldName] = value
        } else if (item.formType === 'map_address') {
          // 地图类型
          if (this.addressData) {
            form.entity.address = this.addressData.address
              ? this.addressData.address.join(',')
              : ''
            form.entity.detailAddress = this.addressData.detailAddress
            form.entity.location = this.addressData.location
            form.entity.lng = this.addressData.lng
            form.entity.lat = this.addressData.lat
          }
        } else {
          const fieldItem = objDeepCopy(item)
          delete fieldItem.field
          delete fieldItem.request
          delete fieldItem.params
          delete fieldItem.props
          delete fieldItem.className
          delete fieldItem.companyId

          form.field.push({
            ...fieldItem,
            value: value
          })
        }
      })

      // 图片信息
      this.imageFields.forEach(item => {
        if (item.fieldType == 1) {
          form.entity[item.fieldName] = this.imageFrom[item.fieldName]
        } else {
          const fieldItem = objDeepCopy(item)
          delete fieldItem.field
          delete fieldItem.request
          delete fieldItem.params
          delete fieldItem.props
          delete fieldItem.className
          delete fieldItem.companyId

          form.field.push({
            ...fieldItem,
            value: this.imageFrom[item.fieldName]
          })
        }
      })

      if (this.id) {
        form.entity[this.typeObj.primaryKey] = this.id
        form.entity.batchId = this.batchId
        const data = this.staticFieldsLib[this.typeObj.hump]
        console.log(data)
        if (!form.entity.hasOwnProperty('ownerUserId') && data.ownerUserId) {
          form.entity.ownerUserId = data.ownerUserId
        }
      }

      form = this.getSavedProduct(form)
      return form
    },

    /**
     * 获取需要保存的产品数据
     */
    getSavedProduct(form) {
      console.log('save form: ', this.productSizeForm)
      if (this.type === 'jxc_product') {
        // 产品
        form.entity.productIshelf = form.entity.productIshelf === '上架' ? 1 : 0
        form.entity.productIsp = this.productSizeForm.openStatus
        if (this.productSizeForm.openStatus === 1 &&
          this.productSizeForm.jxcProductSpecificationsList.length === 0 &&
          this.productSizeForm.jxcProductSpecificationsDataList.length === 0) {
          this.$message.error('规格不能为空')
          return null
        }
        if (this.productSizeForm.openStatus === 1) {
          const filterLen = this.productSizeForm.jxcProductSpecificationsList
            .filter(o => !o.specificationsName || !o.specificationsValue).length
          if (filterLen > 0) {
            this.$message.error('规格名和规格值不能为空')
            return null
          }
        }
        form = {
          ...form,
          ...this.productSizeForm
        }
        if (this.id) {
          form.entity.spBatchId = this.staticFieldsLib.jxcProduct.spBatchId
          form.entity.productIsp = this.staticFieldsLib.jxcProduct.productIsp
        }
        delete form.openStatus
      } else if (this.type === 'jxc_purchase') {
        // 采购
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.purchasesNumber).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcPurchasesProductList = this.productList.map(o => {
          return {
            batchId: o.batchId || '',
            productId: o.productId,
            purchasesNumber: o.purchasesNumber,
            purchasesPrice: o.purchasesPrice,
            purchasesSubtotal: o.purchasesSubtotal,
            discount: o.discount
          }
        })
        const arr = this.productList.map(o => o.purchasesNumber)
        let total = 0
        arr.forEach(num => {
          total += num
        })
        form.entity.productNumber = total
        form.entity.discount = this.baseForm.discount || 0
      } else if (this.type === 'jxc_retreat') {
        // 采购退货
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.retreatNumber).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcRetreatProductList = this.productList.map(o => {
          return {
            // batchId: o.batchId || '',
            retreatNumber: o.retreatNumber,
            retreatPrice: o.retreatPrice,
            // productId: o.purchaseProductId,
            purchaseProductId: o.purchaseProductId,
            retreatSubtotal: o.retreatSubtotal
          }
        })
        const arr = this.productList.map(o => o.retreatNumber)
        let total = 0
        arr.forEach(num => {
          total += num
        })
        form.entity.productNumber = total
      } else if (this.type === 'jxc_sale') {
        // 销售订单
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.saleProductNumber).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcSaleProductList = this.productList.map(o => {
          return {
            batchId: o.batchId || '',
            productId: o.productId,
            saleProductId: o.productId,
            saleProductNumber: o.saleProductNumber,
            saleProductPrice: o.saleProductPrice,
            saleProductSubtotal: o.saleProductSubtotal,
            discount: o.discount
          }
        })
        form.entity.discount = this.baseForm.discount || 0
      } else if (this.type === 'jxc_salereturn') {
        // 销售退货
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.salereturnNumber).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcSalereturnProductList = this.productList.map(o => {
          return {
            batchId: o.batchId || '',
            saleProductId: o.saleProductId,
            salereturnNumber: o.salereturnNumber,
            salereturnPrice: o.salereturnPrice,
            salereturnSubtotal: o.salereturnSubtotal
          }
        })
      } else if (this.type === 'jxc_receipt') {
        // 入库单
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.num).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcReceiptProductList = this.productList.map(o => {
          return {
            batchId: o.batchId || '',
            productId: o.productId,
            receiptNumber: o.num,
            relationId: o.relationId,
            remarks: o.remarks,
            warehouseId: this.relativeData.warehouseId
          }
        })
      } else if (this.type === 'jxc_outbound') {
        // 出库单
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.num).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcOutboundProductList = this.productList.map(o => {
          return {
            batchId: o.batchId || '',
            productId: o.productId,
            outboundProductNumber: o.num,
            relationId: o.relationId,
            remarks: o.remarks,
            warehouseId: this.relativeData.warehouseId
          }
        })
      } else if (this.type === 'jxc_allocation') {
        // 调拨
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        const findLen = this.productList.filter(o => !o.allocationNumber).length
        if (findLen !== 0) {
          this.$message.error('请输入产品数量')
          return null
        }
        form.jxcAllocationProductList = this.productList.map(o => {
          return {
            allocationNumber: o.allocationNumber,
            batchId: o.batchId || '',
            productId: o.productId,
            remarks: o.remarks
          }
        })
      } else if (this.type === 'jxc_inventory') {
        // 盘点
        if (!this.productList || this.productList.length === 0) {
          this.$message.error('请选择产品')
          return null
        }
        form.jxcInventoryProductList = this.productList.map(o => {
          return {
            actualNumber: o.actualNumber,
            batchId: o.batchId || '',
            lossNumber: o.lossNumber,
            productId: o.productId,
            remarks: o.remarks,
            warehouseId: this.relativeData.warehouseId
          }
        })
      }
      return form
    },

    updateForm() {
      this.showForm = false
      this.$nextTick(() => {
        this.showForm = true
      })
    },

    /**
     * 获取请求
     */
    getSaveRequest() {
      return {
        'jxc_product': jxcProductAddOrUpdateAPI,
        'jxc_supplier': jxcSupplierAddOrUpdateAPI,
        'jxc_purchase': jxcPurchaseAddOrUpdateAPI,
        'jxc_retreat': jxcRetreatAddOrUpdateAPI,
        'jxc_sale': jxcSaleAddOrUpdateAPI,
        'jxc_salereturn': jxcSalereturnAddOrUpdateAPI,
        'jxc_receipt': jxcReceiptAddOrUpdateAPI,
        'jxc_outbound': jxcOutboundAddOrUpdateAPI,
        'jxc_collection': jxcCollectionAddOrUpdateAPI,
        'jxc_payment': jxcPaymentAddOrUpdateAPI,
        'jxc_allocation': jxcAllocationAddOrUpdateAPI,
        'jxc_inventory': jxcInventoryAddOrUpdateAPI
      }[this.type] || null
    },

    /**
     * 产品中需要同步修改的字段
     */
    handleSyncFields(data = []) {
      this.syncProductFields = data
    },

    /**
     * 验证编号规则唯一
     */
    checkCodeOnly() {},

    /**
     * 保存
     */
    handleSave() {
      if (this.loading) return
      this.loading = true
      const instance = this.$refs.wkFormBase.instance

      instance.validate(async valid => {
        if (valid) {
          const params = this.getSaveData()
          if (!params) {
            this.loading = false
            return
          }
          if (this.type === 'jxc_allocation' &&
            params.entity.currentWarehouseId == params.entity.originalWarehouseId) {
            this.$message.error('调入仓库不能和调出仓库相同')
            this.loading = false
            return
          }

          if (this.showReceiveAddress) {
            const address = await this.getReceiveAddress()
            params.entity = {
              ...params.entity,
              ...address
            }
          }

          if (this.type === 'jxc_product') {
            if (this.id) {
              params.syncFields = this.syncProductFields
            }
            // 如何是产品编辑/新建则去验证产品编号是否重复
            const codeList = params.jxcProductSpecificationsDataList.map(o => o.spDataCode)
            const filterCodeList = codeList.filter(o => !!o)
            if (filterCodeList.length !== Array.from(new Set(filterCodeList)).length) {
              this.loading = false
              this.$message.error('产品编号不能重复')
              return
            }
            const promiseArr = []
            let hasEmpty = false
            codeList.forEach(code => {
              const p = {
                fieldName: 'productCode',
                fieldType: 1,
                label: this.typeObj.label,
                value: code
              }
              if (this.batchId) {
                // p.batchId = this.staticFieldsLib.jxcProduct.spBatchId
                p.batchId = this.batchId
              }
              if (!code && this.autoGeneNumber) {
                hasEmpty = true
              } else {
                promiseArr.push(jxcFieldOnlyAPI(p))
              }
            })
            if (hasEmpty) {
              promiseArr.push(jxcFieldOderNumberOnlyAPI({
                label: this.typeObj.label
              }))
            }
            let error = null
            await Promise.all(promiseArr).then(resArr => {
              const find = resArr.find(o => !o.data)
              if (find) {
                error = true
                return Promise.reject()
              }
            }).catch(() => {
              error = true
            })
            if (error) {
              this.loading = false
              this.$message.error('产品编号不能重复')
              return
            }
          } else if (this.autoGeneNumber) {
            const key = this.autoNumberField.fieldName
            const code = params.entity[key]
            if (!code) {
              const res = await new Promise((resolve, reject) => {
                jxcFieldOderNumberOnlyAPI({
                  label: this.typeObj.label
                }).then(res => {
                  if (!res.data) {
                    resolve(false)
                  } else {
                    resolve(true)
                  }
                }).catch(() => {
                  resolve(false)
                })
              })
              if (!res) {
                this.loading = false
                this.$message.error('自动编号有重复')
                return
              }
            }
          }

          if (this.showExamine) {
            // 验证审批数据
            let error = false
            const userId = await this.$refs.examineInfo.validateField().catch(() => {
              error = true
            })
            if (error) {
              this.loading = false
              return
            }
            params.checkUserId = userId || ''
            params.entity.state = 2
          }
          if (this.examineTypes.includes(this.type) && !this.showExamine) {
            params.entity.state = 3
          }

          console.log('save', params)
          // this.loading = false
          const request = this.getSaveRequest()
          request(params, Boolean(this.id)).then(() => {
            this.handleClose()
            this.$message.success('保存成功')
            this.$emit('update')
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          // 弹出第一个错误
          this.loading = false
          if (instance.fields) {
            for (
              let index = 0;
              index < instance.fields.length;
              index++
            ) {
              const ruleField = instance.fields[index]
              if (ruleField.validateState == 'error') {
                this.$message.error(ruleField.validateMessage)
                break
              }
            }
          }
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

.create-container {
  position: relative;
  height: 100%;
  .create-header {
    height: 40px;
    margin-bottom: 20px;
    padding: 0 10px;
    .create-header_title {
      font-size: 17px;
      color: #333;
      font-weight: bold;
    }
    .create-header_close {
      font-size: 24px;
      color: #999;
      cursor: pointer;
      &:hover {
        color: $xr-color-primary;
      }
    }
  }

  .create-body {
    width: 100%;
    overflow-x: hidden;
    overflow-y: auto;

    /deep/ .create-sections-content {
      margin-top: 15px;
    }

    .wk-form {
      // margin: 0;
    }
  }

  .create-footer {
    width: 100%;
    text-align: right;
    margin-top: 5px;
    .el-button {
      margin-left: 0;
      margin-right: 20px;
    }
  }
}

// 审核信息 里的审核类型
.examine-type {
  font-size: 12px;
  color: white;
  background-color: #fd715a;
  padding: 0 8px;
  margin-left: 5px;
  height: 16px;
  line-height: 16px;
  border-radius: 8px;
  transform: scale(0.8, 0.8);
}

/deep/ .wk-user-select,
/deep/ .wk-dep-select {
  margin: 3px 0;
}
/deep/ .block_one_line {
  flex: unset !important;
  width: 100%;
}
</style>
